import request from 'umi-request';
import { Toast } from 'antd-mobile';

request.interceptors.request.use((url: any, options: any) => {
  //判断本地session是否有数据，如果有就得到token，并付给请求头
  if (localStorage.getItem('hunliji_token') != null) {
    console.log(`options`, options);
    if (options.method != 'POST') {
      Toast.show({
        icon: 'loading',
        content: '数据加载中…',
      });
    }
    //获取到存在本地session里存的数据
    let c_token: any = localStorage.getItem('hunliji_token');
    //转换获取到的数据格式，得到里面的token
    const headers = {
      Authorization: c_token,
    };
    return {
      url,
      options: { ...options, headers },
    };
  }
});

request.interceptors.response.use(async (response: any, options: any) => {
  const data = await response.clone().json();
  // 判断token是否过期
  if (data.status == 400) {
    localStorage.removeItem('hunliji_token');
    return response;
  } else if (options.method == 'POST') {
    return response;
  } else {
    Toast.show({
      content: '数据加载完成',
      duration: 1000,
    });
    return response;
  }
});
